<?php

namespace App\Handlers;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use Salman\Mqtt\MqttClass\Mqtt;
use App\Models\Device;
use App\Models\SwitchData;
use App\Models\BatteryConfig;

class MqttHandler
{

    public static function SubscribetoTopic($topic, $type)
    {
        $mqtt = new Mqtt();
        $mqtt->ConnectAndSubscribe($topic, function($topic, $msg) use($type) {
            echo "Msg Received: \n";
            echo "Topic: {$topic}\n\n";
            echo "\t$msg\n\n";
            if ($type == 'bettery') {
                BatteryConfig::analysisMessage($topic, $msg);
            }
        });
    }

    public static function SubscribetoTopicOnce($topic, $type)
    {
        $mqtt = new Mqtt();
        $mqtt->ConnectAndSubscribe($topic, function($topic, $msg) use($type) {
            echo "Msg Received: \n";
            echo "Topic: {$topic}\n\n";
            echo "\t$msg\n\n";
            return;
        });
    }

    public static function SendMsgViaMqtt($uniqueCode, $switchId, $cmd, $status)
    {
        $topic = 'hongfa/'.$uniqueCode.'/download/';

        $mqtt = new Mqtt();
        $output = $mqtt->ConnectAndPublish($topic, $cmd);
        if ($output === true) {
            $last = SwitchData::where('switch_id', $switchId)->orderBy('created_time', 'desc')->first();
            $data = json_decode($last['data'], true);
            $data['status'] = intval($status);
            $last->data = json_encode($data);
            $last->save();
            return true;
        } else {
            return false;
        }
    }
}